import { Session } from "@/utils/storage";
import { store } from "@/store/index";
import { getMenuAdmin } from "@/api/system/menu/index";
import { dynamicRoutes } from "@/router/router";
import { getRouters } from "@/api/menu"
import {
  setAddRoute,
  setFilterMenuAndCacheTagsViewRoutes,
} from "@/router/index";
import Parent from "@/layout/routerView/parent.vue";
import Link from "@/layout/routerView/link.vue";
import Iframe from "@/layout/routerView/iframes.vue";

//import Layout from "@/layout/index";
//import ParentView from "@/components/ParentView";
//import InnerLink from "@/layout/components/InnerLink";

//const layouModules: any = import.meta.glob('../layout/routerView/*.{vue,tsx}');
//const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}');

const loadLayout = (view) => {
  // 路由懒加载
  //debugger;
  return (resolve) => require([`@/layout/routerView/${view}`], resolve);
  //return () => import(`@/layout/routerView/${view}`);
};

const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve);
};

const layouModules = require.context("../layout/routerView/", true, /\.vue$/);
const obj1 = new Object();
layouModules.keys().forEach((key) => {
  const obj_key = "../layout/routerView/" + key.slice(2);
  const obj_value = key.slice(2);
  obj1[obj_key] = loadLayout(obj_value);
});

const viewsModules = require.context("../views/", true, /\.vue$/);
const obj2 = new Object();
viewsModules.keys().forEach((key) => {
  const obj_key = "../views/" + key.slice(2);
  const obj_value = key.slice(2);
  obj1[obj_key] = loadView(obj_value);
});

const dynamicViewsModules = Object.assign({}, { ...obj1 }, { ...obj2 });

export async function initBackEndControlRoutes() {
  //debugger;
  // 无 token 停止执行下一步
  if (!Session.get("token")) return false;
  // 触发初始化用户信息

  //const store = useStore();

  store.dispatch("userInfos/setUserInfos");
  // 获取路由菜单数据
  const res = await getBackEndControlRoutes();

  // 存储接口原始路由（未处理component），根据需求选择使用
  store.dispatch(
    "requestOldRoutes/setBackEndControlRoutes",
    JSON.parse(JSON.stringify(res.data))
  );

  const arr = await backEndComponent(res.data);
  dynamicRoutes[0].children = arr

  // 添加动态路由
  await setAddRoute();
  // 设置递归过滤有权限的路由到 vuex routesList 中（已处理成多级嵌套路由）及缓存多级嵌套数组处理后的一维数组
  setFilterMenuAndCacheTagsViewRoutes();
}

/**
 * 后端路由 component 转换
 * @param routes 后端返回的路由表数组
 * @returns 返回处理成函数后的 component
 */
export function backEndComponent(routes) {
  if (!routes) return;
  return routes.map((item) => {
    if (item.component)
      //item.component = dynamicImport(dynamicViewsModules, item.component);
      item.component = dynamicImport2(item.component)
    item.children && backEndComponent(item.children);
    return item;
  });
}

export function dynamicImport(dynamicViewsModules, component) {
  //debugger;
  const keys = Object.keys(dynamicViewsModules);
  const matchKeys = keys.filter((key) => {
    const k = key.replace(/..\/views|../, "");
    return k.startsWith(`${component}`) || k.startsWith(`/${component}`);
  });
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0];
    //return dynamicViewsModules[matchKey];
    const comKey = matchKey.slice(3);
    //return (resolve) => require([`@/${comKey}`], resolve);
    return () => import(`@/${comKey}`);
  }
  if (matchKeys?.length > 1) {
    return false;
  }
}

export function dynamicImport2 (component) {
  if (component) {
    // Layout ParentView 组件特殊处理
    if (component === 'Layout') {
      component = Parent
    } else if (component === 'OuterLink') {
      component = Link
    } else if (component === 'InnerLink') {
      component = Iframe
    } else {
      component = loadComponent(component)
    }
  }
  return component;
}

export function getBackEndControlRoutes() {
  // 模拟 admin 与 test
  //const auth = store.state.userInfos.userInfos.roles[0];
  // 管理员 admin
  //if (auth === "admin") return getMenuAdmin();
  // 其它用户 test
  //else return getMenuTest();
  //return getData();
  //return getMenuAdmin();
  return getRouters();
}

const loadComponent = (view) => {
  // 路由懒加载
  // return (resolve) => require([`@/${view}`], resolve);
  return () => import(`@/${view}`);
}
